package Inet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket clientSocket = null;

    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        clientSocket = new Socket(serverIp,serverPort);
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scannerNet = new Scanner(inputStream);
            while (true) {
                //1、从控制台读取数据
                System.out.print("请输入要发送的请求->");
                String request = scanner.next();
                //2、把请求发送给服务器
                request += "\n";
                outputStream.write(request.getBytes());
                //3、从服务器读取到响应
                if (!scannerNet.hasNext()) {
                    break;
                }
                String response = scannerNet.next();
                //4、把响应打印到控制台上
                System.out.println(response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}
